﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;

namespace Pay.Token {
    public static class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            // Web API 配置和服务
            // Web API configuration and services
            var json = config.Formatters.JsonFormatter;
            // 解决json序列化时的循环引用问题
            json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            //json.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            //格式化时间
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            json.SerializerSettings.Converters.Add(timeConverter);
            //将NULL转为""
            //config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new NullToEmptyStringResolver();
            // 干掉XML序列化器
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            // Web API 配置和服务
            config.MessageHandlers.Add(new AuthenticationHandler());
            config.Filters.Add(new WebApiExceptionFilterAttribute());
            //config.Services.Replace(typeof(IHttpControllerSelector), new NotFoundControllerSelector(config));
            //config.Services.Replace(typeof(IHttpActionSelector), new NotFoundActionSelector());
            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //config.Routes.MapHttpRoute(
            //    name: "Error404",
            //    routeTemplate: "{*url}",
            //    defaults: new { controller = "Error", action = "Handle404" }
            //);
        }
    }
}